using SqlSugar;
using WebApp8.Models;

namespace WebApp8.Services
{
    public class DbContext
    {
        public SqlSugarScope Db { get; }

        public DbContext(IConfiguration configuration)
        {
            var dbConfig = configuration.GetSection("DbConfig").Get<MultiDbConfig>();
            
            var connectionConfigs = new List<ConnectionConfig>
            {
                new ConnectionConfig
                {
                    ConfigId = "Oracle",
                    ConnectionString = dbConfig?.Oracle.ConnectionString,
                    DbType = DbType.Oracle,
                    IsAutoCloseConnection = true,
                    AopEvents = new AopEvents
                    {
                        OnLogExecuting = (sql, parameters) =>
                        {
                            if (dbConfig?.Oracle.EnableLogging == true)
                                Console.WriteLine($"Oracle SQL: {sql}");
                        }
                    }
                },
                new ConnectionConfig
                {
                    ConfigId = "SqlServer",
                    ConnectionString = dbConfig?.SqlServer.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    AopEvents = new AopEvents
                    {
                        OnLogExecuting = (sql, parameters) =>
                        {
                            if (dbConfig?.SqlServer.EnableLogging == true)
                                Console.WriteLine($"SqlServer SQL: {sql}");
                        }
                    }
                },
                new ConnectionConfig
                {
                    ConfigId = "MySql",
                    ConnectionString = dbConfig?.MySql.ConnectionString,
                    DbType = DbType.MySql,
                    IsAutoCloseConnection = true,
                    AopEvents = new AopEvents
                    {
                        OnLogExecuting = (sql, parameters) =>
                        {
                            if (dbConfig?.MySql.EnableLogging == true)
                                Console.WriteLine($"MySql SQL: {sql}");
                        }
                    }
                }
            };

            Db = new SqlSugarScope(connectionConfigs);
        }

        // 获取指定数据库的SimpleClient
        public SimpleClient<T> GetDb<T>(string configId) where T : class, new()
        {
            return new SimpleClient<T>(Db.GetConnection(configId));
        }
    }
} 